package com.choudou5.solr.core.util;

import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.SolrCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;

/**
 * @Name：SolrHelper
 * @@author choudou5
 * @@date 2018-07-15
 */
public class SolrHelper {

    protected static final Logger LOGGER = LoggerFactory.getLogger(SolrHelper.class);

    private static volatile CoreContainer coreContainer;


    public static void initCacheCoreContainer(final CoreContainer coreContainer){
        SolrHelper.coreContainer = coreContainer;
    }

    /**
     * 获取容器的Bean
     * @param coreName
     * @return SolrCore
     */
    public static SolrCore getCore(String coreName) {
        try{
            LOGGER.info("getCore:" + coreName);
            return coreContainer.getCore(coreName);
        }catch(Exception ex){
            LOGGER.error("getCore:" + coreName + "," + ex.getMessage());
        }
        return null;
    }

    /**
     * 移除
     * @param coreName
     * @param deleteData 是否删除数据
     */
    public static void unload(String coreName, boolean deleteData) {
        try{
            coreContainer.unload(coreName, deleteData, deleteData, deleteData);
        }catch(Exception ex){
            LOGGER.debug("unload:" + coreName + "," + ex.getMessage());
        }
    }


    public static boolean existCoreName(String coreName){
        if (coreContainer.getAllCoreNames().contains(coreName)) {
            LOGGER.warn("Creating a core with existing name is not allowed");
            return true;
        }
        return false;
    }

    public static Collection<String> getCoreNameList(){
        return coreContainer.getAllCoreNames();
    }


    public static String getSolrHome() {
        return coreContainer.getSolrHome();
    }

    public static boolean isZkModel() {
        return coreContainer.isZooKeeperAware();
    }

    public static CoreContainer getCoreContainer() {
        return coreContainer;
    }
}
